Sets are unordered collections of unique elements. They are versatile data structures used for tasks like:
Removing duplicates from a sequence
✦ Checking membership (efficiently determining if an element is present)
✦ Performing set operations (union, intersection, difference)
Key characteristics of sets:
✦
Unordered: The order in which elements are added or appear in the set is not guaranteed.
✦
Unique Elements: Duplicate values are not allowed. If you try to add a duplicate, it will be silently ignored.
✦
Mutable: Sets themselves can be modified (adding, removing elements), but the elements within a set must be immutable (unchangeable). This means you cannot modify elements like lists or dictionaries within a set after they're added.
Creating Sets
There are several ways to create sets in Python:
1. Curly Braces {}:
The most common way is to enclose elements within curly braces, separated by commas.
Creating set using Curly Braces {} in python
my_set = {1, "apple", 3.14}
print(my_set)
print(type(my_set))
Output
{1, 3.14, 'apple'}
2. set() Constructor:
The set() constructor can be used to create sets from various iterables (lists, tuples, strings). It automatically removes duplicates.
Creating set using set() constructor in python
my_list = [1, 2, 2, 3, "apple", "apple"]
my_set = set(my_list)
print("list Before : ",my_list)
print("list After : ",my_set)
my_tuple = (1, 4, 1, 5)
my_set = set(my_tuple)
print("tuple Before : ",my_tuple)
print("tuple after : ",my_set)
Output
list Before : [1, 2, 2, 3, 'apple', 'apple']
list After : {1, 2, 3, 'apple'}
tuple Before : (1, 4, 1, 5)
tuple after : {1, 4, 5}
3. Comprehension (Advanced):
For more complex set creation logic, you can use set comprehensions.
Creating set using set comprehension example in python
numbers = {x for x in range(1, 6) if x % 2 == 0}
print(numbers)
Output
{2,4}
Additional Notes:
When creating sets from sequences containing mutable elements (like lists), those elements within the set remain immutable.
Sets are hash-based, making membership checks (in operator) very efficient (average time complexity of O(1)).
Example Usage:
Set example in python
fruits = {"apple", "banana", "cherry"}
# Check membership
if "orange" in fruits:
print("Orange is in the set")
else:
print("Orange is not in the set")
# Add an element
fruits.add("mango")
# Remove an element (raises KeyError if element not found)
fruits.remove("cherry")
# Set operations (demonstrated here using methods)
unique_fruits = fruits.union({"mango", "pineapple"})
common_fruits = fruits.intersection({"mango", "grapefruit"})
different_fruits = fruits.difference({"mango", "grapefruit"})
print("Original fruits:", fruits)
print("Unique fruits:", unique_fruits)
print("Common fruits:", common_fruits)
print("Different fruits:", different_fruits)
Output
Orange is not in the set
Original fruits: {'apple', 'banana', 'mango'}
Unique fruits: {'banana', 'pineapple', 'apple', 'mango'}
Common fruits: {'mango'}
Different fruits: {'apple', 'banana'}